package com.spdb.spdbfl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.spdb.spdbfl.config.BaseConfig;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

public class Login {

    public static final String login_url = BaseConfig.domainUrl + "/auth/login";
    public String user = "admin";
    public static final String password = "1";

    /**
     * 登陆获取token
     * @param account
     * @param password
     * @return
     */
    public String getToken(String account, String password){
        System.out.println("登陆账户account...");
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", account);
        jsonObject.put("password", password);

        HttpEntity httpEntity = new HttpEntity(jsonObject.toJSONString(), requestHeaders);
        System.out.println("httpEntity : "+httpEntity);
        ParameterizedTypeReference<String> params = new ParameterizedTypeReference<String>() {
        };
        RestTemplate restTemplate = new RestTemplate();
//        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        ResponseEntity<String> response=null;
        try{
            response = restTemplate.exchange(login_url, HttpMethod.POST, httpEntity, params);
            String result = response.getBody();
            System.out.println("getToken接口正常返回: "+result);
            JSONObject jsonObject1 = JSONObject.parseObject(result);
            JSONObject data = (JSONObject) jsonObject1.get("data");
            String token = (String) data.get("token");
            System.out.println("token值:" + token);
            //更新用户的token配置
            String accountToken = account + "Token";
            ConfigProperty.updateProperty(accountToken, token);
            Thread.sleep(3000);
            return token;
        }catch (HttpClientErrorException e){
            String responseBody = e.getResponseBodyAsString();
            System.out.println("getToken接口异常返回："+ JSON.toJSONString(responseBody));
            return e.getMessage();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static void main(String[] args) {
        Login login = new Login();
        login.getToken("lium", "1");
    }
}
